﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.ServiceModel;
using DataContracts;
using ServiceContracts;


namespace Presention
{
    public partial class MainSearch : System.Web.UI.Page
    {
        public double pageSize = Convert.ToDouble(ConfigurationManager.AppSettings["PageSize"]);

        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!IsPostBack)
            {

                this.RoleSearchGridView.Attributes.Add("SortExpression", "LevelName");
                this.RoleSearchGridView.Attributes.Add("SortDirection", "ASC");
                Session["sortexpressin"] = "LevelName";
                Session["sortdirection"] = "ASC";
                Session["pageindex"] = 1;
                Session["pagecount"] = 1;
                Session["pagesize"] = pageSize;

                using (ServiceAgent SA = new ServiceAgent())
                {


                    StatusDropDownList.DataSource = SA.ServiceClient.GetAllRoleStatus();
                    StatusDropDownList.DataTextField = "StatusName";
                    StatusDropDownList.DataValueField = "StatusId";
                    StatusDropDownList.DataBind();
                    StatusDropDownList.Items.Add("Please Select");
                    StatusDropDownList.SelectedValue = "Please Select";

                    AuthorityCheckBoxList.DataSource = SA.ServiceClient.GetAllAuthority();
                    AuthorityCheckBoxList.DataTextField = "AuthorityName";
                    AuthorityCheckBoxList.DataValueField = "AuthorityId";
                    AuthorityCheckBoxList.DataBind();
                }
            }




        }

        /// <summary>
        /// Get the Result and display in GridView
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GenerateReportButton_Click(object sender, EventArgs e)
        {
            //int pageSize = RoleSearchGridView.PageSize;
            //Session["pagesize"] = pageSize;
            string sortExpression = Session["sortexpressin"].ToString();
            string sortDirection = Session["sortdirection"].ToString();

            gridBind(sortExpression, sortDirection, pageSize, 1);

        }

      
        /// <summary>
        /// Implement paging
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RoleSearchGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            
            RoleSearchGridView.PageIndex = e.NewPageIndex;
            //int pageSize = RoleSearchGridView.PageSize;

            int pageIndex = RoleSearchGridView.PageIndex;
            gridBind("levelname", "ASC", pageSize, pageIndex);

        }

        /// <summary>
        /// Implement Sorting
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RoleSearchGridView_Sorting(object sender, GridViewSortEventArgs e)
        {


            //get the sorting data column from event parameters 
            string sortExpression = e.SortExpression.ToString();

            string sortDirection = this.RoleSearchGridView.Attributes["SortDirection"].ToString();

            // compare sorting direction with 'asc',and modified sort direction parameters in GridView
            if (sortExpression == this.RoleSearchGridView.Attributes["SortExpression"])
            {
                //Get the next sorting state
                string a = this.RoleSearchGridView.Attributes["SortDirection"].ToString();
                
                if (a == "ASC")
                {
                    sortDirection = "DESC";
                }
                else
                {
                    sortDirection = "ASC";
                }
            }
            else
            {
                sortDirection = "ASC";
            }


            // reset sort datacoloum and sort direction in GridView
            this.RoleSearchGridView.Attributes.Remove("SortExpression");
            this.RoleSearchGridView.Attributes.Remove("SortDirection");
            this.RoleSearchGridView.Attributes.Add("SortExpression", sortExpression);
            this.RoleSearchGridView.Attributes.Add("SortDirection", sortDirection);
            //int pageSize = RoleSearchGridView.PageSize;
            Session["sortexpressin"] = sortExpression;
            Session["sortdirection"] = sortDirection;

            ArrowShow(sortDirection,sortExpression,RoleSearchGridView);

            gridBind(sortExpression, sortDirection, pageSize, 1);


        }

        /// <summary>
        /// Binding GridView DataSource
        /// </summary>
        /// <param name="sortExpression"></param>
        /// <param name="sortDirection"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        public void gridBind(string sortExpression, string sortDirection, double pageSize, int pageIndex)
        {
            string roleName = RoleNameTextBox.Text.Trim();
            //string userName = UserTextBox.Text.Trim();
            string authorities = "";
            //string firstName = "";
            //string lastName = "";
            string status = StatusDropDownList.SelectedItem.Text;
            //string[] nameSplit = userName.Split(' ');
            // List<Role> RolePageNum = new List<Role>();
            int pageCnt = 0;
            Session["pageindex"] = pageIndex;
            if (status == "Please Select")
            {
                status = "";
            }

            //if (nameSplit.Length == 1)
            //{
            //    firstName = nameSplit[0];
            //    lastName = "";
            //}
            //else if (nameSplit.Length == 2)
            //{
            //    firstName = nameSplit[0];
            //    lastName = nameSplit[1];
            //}
            //else
            //{

            //}

            List<string> authorityList = new List<string>();

            for (int i = 0; i < AuthorityCheckBoxList.Items.Count; i++)
            {
                if (AuthorityCheckBoxList.Items[i].Selected)
                    authorityList.Add(AuthorityCheckBoxList.Items[i].Text);
            }

            if (authorityList.Count > 0)
            {
                for (int j = 0; j < authorityList.Count; j++)
                {
                    authorities += authorityList[j];
                    authorities += ",";
                }
                //int lastId = authorityList.Count - 1;
                //authorities += AuthorityCheckBoxList.Items[lastId].Text;
                authorities.TrimEnd(',');
            }

            List<RoleViewDTO> roleList = new List<RoleViewDTO>();

            using (ServiceAgent SA = new ServiceAgent())
            {
                roleList = SA.ServiceClient.SearchRole(roleName, status, authorities, sortExpression, sortDirection, pageSize, pageIndex, out pageCnt);

                if (roleList.Count == 0)
                {
                    Page.RegisterStartupScript("", "<script language='javascript'>window.alert('The query result is null!');</script>");
                    // Response.Write("<Script language='JavaScript'> alert('The query result is null! ')</Script>");
                }


                RoleSearchGridView.DataSource = roleList;
                RoleSearchGridView.DataBind();

            }

            if (pageCnt != 0)
            {
                //if(RolePageNum[0].PageCount > 0)error

                Session["pagecount"] = pageCnt;

                if (pageCnt == 1)
                {
                    IsOrNotShow(false);

                }

                else
                {
                    IsOrNotShow(true);

                    lblCount.Text = Session["pagecount"].ToString();
                    lblCurrentInfo.Text = pageIndex.ToString();
                }
            }
            else
            {
                IsOrNotShow(false);
            }


            //RoleSearchGridView.PageCount is a readonly property
        }

        /// <summary>
        /// Navigate Page Index
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void PageIndex_Changed(object sender, EventArgs e)
        {

            string sortExpression = Session["sortexpressin"].ToString();
            string sortDirection = Session["sortdirection"].ToString();
            int pageSize = Convert.ToInt32(Session["pagesize"]);
            int pageIndex = Convert.ToInt32(Session["pageindex"]);
            int pageCount = Convert.ToInt32(Session["pagecount"]);

            LinkButton lb = (LinkButton)sender;
            if (lb.ID == "lbtnFirst")
            {
                gridBind(sortExpression, sortDirection, pageSize, 1);
            }
            else if (lb.ID == "lbtnPrev")
            {
                if (pageIndex > 1)
                {
                    gridBind(sortExpression, sortDirection, pageSize, pageIndex - 1);
                }


            }
            else if (lb.ID == "lbtnNext")
            {
                if (pageIndex < pageCount)
                {
                    gridBind(sortExpression, sortDirection, pageSize, pageIndex + 1);
                }
            }
            else
            {

                gridBind(sortExpression, sortDirection, pageSize, pageCount);
            }

        }

        /// <summary>
        /// judge whether GridView control is visible
        /// </summary>
        /// <param name="falseOrTrue"></param>
        public void IsOrNotShow(bool falseOrTrue)
        {
            lbtnFirst.Visible = falseOrTrue;
            lbtnLast.Visible = falseOrTrue;
            lbtnPrev.Visible = falseOrTrue;
            lbtnNext.Visible = falseOrTrue;
            lbtnLast.Visible = falseOrTrue;
            lblCount.Visible = falseOrTrue;
            lblCurrentInfo.Visible = falseOrTrue;
            Label1.Visible = falseOrTrue;
        }

        /// <summary>
        /// implement sorting according to parameters
        /// </summary>
        /// <param name="sortDirection"></param>
        /// <param name="sortExpression"></param>
        /// <param name="gridView"></param>
        public void ArrowShow(string sortDirection, string sortExpression,GridView gridView)
        {
            string[] gridViewHeaderName={"RoleId","RoleName","AuthorityName","LevelName"};

            for(int i=0;i<4;i++)
                {
                 if (sortExpression==gridViewHeaderName[i])
                    {
                     
                     if (sortDirection == "ASC")

                        gridView.Columns[i].HeaderText =gridViewHeaderName[i] + "<font face=webdings>5</font>";
                         
                     else
                         gridView.Columns[i].HeaderText =gridViewHeaderName[i] + "<font face=webdings>6</font>";

                    }
                 else
                 
                     gridView.Columns[i].HeaderText =gridViewHeaderName[i];
                 
                }

                }
            
               
            }

    }
